package com.practice.生成token的几种方式.thwautho;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.practice.生成token的几种方式.User;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by IntelliJ IDEA2021.3
 * @Author: Tenghw
 * @Date: 2022/12/03  20:55
 * @Description:
 */
@SuppressWarnings("all")
public class JWTUtils {

    //签名,下面作为私钥用的(也可用密码加密，作为私钥)
    private final static String signature = "user";
    //过期时间24h
    private static final long TIME = 1000 * 60 * 60 * 24;

    public static String jwt(User user) {
        //构建JWT对象
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create()
                .withHeader(map)		//设置header
                .withClaim("username", user.getName())		//设置payload载荷
                .withClaim("id", user.getId())
                .withExpiresAt(new Date(System.currentTimeMillis() + TIME)) //token 过期时间
                .sign(Algorithm.HMAC256(signature));        //token加签 内容不重要

    }
}
